package com.heima.comment.service.Impl;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVO;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private GreenScan greenScan;
    @Autowired
    UserFeign userFeign;
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
//        1.校验参数
//        评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数异常!");
        }
        if (dto.getSize()==null||dto.getSize()==0) {
            dto.setSize(10);
        }
        if (dto.getMinDate()==null) {
            dto.setMinDate(new Date());
        }
//        2. 条件查询评论回复信息
//	条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        query.limit(dto.getSize());
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
//        3. 检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
//	3.1 如果未登录直接 返回评论回复列表
        if (user == null) {
            return ResponseResult.okResult(apCommentRepays);
        }
//	3.2 如果登录，需要判断哪些回复点过赞
//	思路:

//     基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
//	     遍历 当前回复列表，将每一个回复信息 封装成 vo
//	     判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
        ArrayList<String> list = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : apCommentRepays) {
            list.add(apCommentRepay.getId());
        }
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(Query.query(Criteria.where("commentRepayId").in(list).and("authorId").is(user.getId())), ApCommentRepayLike.class);
        ArrayList<ApCommentRepayVO> apCommentRepayVOs = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : apCommentRepays) {
            if (apCommentRepayLikes.size()==0) {
                return ResponseResult.okResult(apCommentRepays);
            }
            for (int i = 0;i<apCommentRepayLikes.size();i++) {
                if (apCommentRepayLikes.get(i).getCommentRepayId().equals(apCommentRepay.getId())) {
                    ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
                    BeanUtils.copyProperties(apCommentRepay,apCommentRepayVO);
                    apCommentRepayVO.setOperation((short)0);
                    apCommentRepayVOs.add(apCommentRepayVO);
                    break;
                }else if(i==apCommentRepayLikes.size()-1){
                    ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
                    BeanUtils.copyProperties(apCommentRepay,apCommentRepayVO);
                    apCommentRepayVOs.add(apCommentRepayVO);
                }
            }
        }
        return ResponseResult.okResult(apCommentRepayVOs);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
//        1. 参数校验:
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数异常!");
        }
//        是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "需要登录后操作!");
        }
//        回复内容安全校验
//          简单: 不校验      普通: 阿里云内容检查，有问题抛异常     困难：阿里云内容检查，有问题替换为**
        ScanResult scanResult = null;
        String filteredContent = "";
        try {
            scanResult = greenScan.greenTextScan(dto.getContent());
            filteredContent = scanResult.getFilteredContent();
        } catch (Exception e) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文本内容违规!");
        }
//        2. 根据评论id查询评论信息  检查是否存在
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("id").is(dto.getCommentId())), ApComment.class);
        if (apComment==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该评论不存在!");
        }
        ResponseResult<ApUser> user = userFeign.findUserById(apUser.getId());
        ApUser apUser1 = user.getData();
//        3. 保存评论回复信息
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        BeanUtils.copyProperties(apComment,apCommentRepay);
        if ("pass".equals(scanResult.getSuggestion())) {
            apCommentRepay.setContent(dto.getContent());
        } else {
            apCommentRepay.setContent(filteredContent);
        }
//            apCommentRepay.setId(UUID.randomUUID().toString());
            apCommentRepay.setLikes(0);
            apCommentRepay.setId(null);
            apCommentRepay.setCommentId(apComment.getId());
            apCommentRepay.setAuthorId(apUser1.getId());
            apCommentRepay.setAuthorName(apUser1.getName());
            mongoTemplate.insert(apCommentRepay);
//        4. 修改评论信息中回复数量 + 1
            apComment.setReply(apComment.getReply()+1);
            mongoTemplate.save(apComment);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
//        1. 校验参数
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数异常!");
        }
//      回复id不能为空   operation 必须 0 或 1
//       校验登录  (必须登录)
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "需要登录后操作!");
        }
//       校验回复信息是否存在
        ApCommentRepay apCommentRepay = mongoTemplate.findOne(Query.query(Criteria.where("id").is(dto.getCommentRepayId())), ApCommentRepay.class);
        if (apCommentRepay==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "回复不存在!");
        }
//        2. 如果是点赞  判断是否点过赞
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId())), ApCommentRepayLike.class);
//      点过赞提示请勿重复点赞
        HashMap<String, Integer> map = new HashMap<>();
        if (dto.getOperation() == 0) {
            if (apCommentRepayLike != null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请不要重复点赞!");
            }
//      未点过赞， 保存点赞信息
            ApCommentRepayLike commentRepayLike = new ApCommentRepayLike();
            BeanUtils.copyProperties(dto,commentRepayLike);
            commentRepayLike.setAuthorId(apUser.getId());
            mongoTemplate.save(commentRepayLike);
//       并将回复信息的点赞数量字段+1
            apCommentRepay.setLikes(apCommentRepay.getLikes()+1);
            mongoTemplate.save(apCommentRepay);
            map.put("likes",apCommentRepay.getLikes());
        }
//        3. 如果是取消赞
        if (dto.getOperation() == 1) {
            //      删除点赞信息
            mongoTemplate.remove(apCommentRepayLike);
            if (apCommentRepay.getLikes() == 0) {
                apCommentRepay.setLikes(1);
                mongoTemplate.save(apCommentRepay);
            }
            //    并将回复信息的点赞数量字段-1
            apCommentRepay.setLikes(apCommentRepay.getLikes() - 1);
            mongoTemplate.save(apCommentRepay);
            map.put("likes", apCommentRepay.getLikes());
        }
//       4. 返回当前回复的最新点赞数量      数据的key:  likes
        return ResponseResult.okResult(map);
    }
}
